package com.tek.ding.faceding.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.util.List;

public class ActivityUtil {

    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static boolean isActivityTop(Activity activity) {
        ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(activity.getClass().getName());
    }

    /**
     * 通过对比topPkgName与targetPkgName是否一致，来判断应用是否运行在最上层。
     * 通过这种方式获取到的topPkgName会出现为空的情况，导致判断异常。与方法一注意事项相同。
     */
    public static boolean getTopActivityPkgName(Context context, String nowPkgName) {
        String topPkgName = "";
        //get top activity package name
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> pis = am.getRunningAppProcesses();
        ActivityManager.RunningAppProcessInfo topAppProcess = pis.get(0);
        if (topAppProcess != null && topAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            topPkgName = topAppProcess.processName;
            System.out.println("topPkgName = " + topPkgName);
            return topPkgName.equals(nowPkgName);
        }
        return false;
    }

    /**
     * 判断应用是否在前台的方法
     */
    public static boolean isAppForeground(Context context) {
        if (null != context) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();
            if (runningProcesses != null) {
                for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                    if (processInfo.processName.equals(context.getPackageName()) && processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}
